<?php

namespace app\common\service;

use app\common\model\CustomPush;
use app\common\model\ExternalSource;
use app\common\model\Member;
use ShidianUtil\Utils\StringUtil;

/**
 * 把新案源推送给律师
 * Class ExternalSourcePushService
 * @package app\common\service
 */
class ExternalSourcePushService
{
    private SubscriptionMessageService $subscriptionMessageService;

    public function __construct(SubscriptionMessageService $subscriptionMessageService)
    {

        $this->subscriptionMessageService = $subscriptionMessageService;
    }

    public function pushToLawyers($id)
    {

        $record = ExternalSource::where('id', $id)
                                ->where('wxStatus', ExternalSource::UNPUSH)
                                ->find();

        if (!$record) {
            return;
        }

        $record->wxStatus = ExternalSource::PUSHING;
        $record->save();

        // 推送
        $wxPushMemberIds = [];
        try {

            $wxPushMemberIds = $this->push($record);
        } finally {

            $record->wxPushMemberIds = $wxPushMemberIds;
            $record->wxStatus = ExternalSource::PUSHED;
            $record->save();
        }

    }

    private function push(ExternalSource $record): array
    {
        $sourceId = $record->sourceId;
        $cityAreasNum = $record->cityAreasNum;
        $sourceType = $record->sourceType;
        $time = $record->created;
        $source = $record->source;

        $type_name = $source['type_name'] ?? '';
        $content = $source['content'] ?? '';
        $remark = $source['remark'] ?? '';
        $province = $source['province'] ?? '';
        $city = $source['city'] ?? '';

        if (is_blank($cityAreasNum)) {
            return [];
        }

        // 城市，类型匹配
        $memberIds = CustomPush::where('pushStatus', 1)
                               ->where(function ($query) use ($cityAreasNum) {
                                   $query->whereRaw("FIND_IN_SET(:cityAreasNum, city)", ['cityAreasNum' => $cityAreasNum], 'OR')
                                         ->whereOr('city', '');
                               })
                               ->where(function ($query) use ($sourceType) {
                                   $query->whereRaw("FIND_IN_SET(:sourceType, sourceType)", ['sourceType' => $sourceType], 'OR')
                                         ->whereOr('sourceType', '全部')
                                         ->whereOr('sourceType', '');
                               })
                               ->select()
                               ->column('memberId');

        // 关键词匹配
        $memberIds2 = CustomPush::where('kwsPushStatus', 1)
                                ->where('kws', '<>', '')
                                ->select()
                                ->filter(function (CustomPush $customPush) use ($content) {
                                    foreach ($customPush->kws as $kw) {
                                        if (StringUtil::contains($content, $kw)) {
                                            return true;
                                        }
                                    }
                                    return false;
                                })
                                ->column('memberId');

        $memberIds = array_values(array_unique(array_merge($memberIds, $memberIds2)));

        if (empty($memberIds)) {
            return [];
        }

        $messageContent = $content;
        if ($type_name == '精选') {
            $messageContent = $remark;
        }

        $members = Member::where('status', 1)
                         ->where(function ($query) {
                             $query->whereOr('type', 1)
                                   ->whereOr('isSettled', '>', 0)
                                   ->whereOr('userPersonnelId', '>', 0);
                         })
                         ->whereIn('id', $memberIds)
                         ->field(['id'])
                         ->select();

        $members->each(fn(Member $member) => $this->subscriptionMessageService->messageNewSource($member->id, $sourceType, $messageContent, $province . '-' . $city, $time, $sourceId));

        return $members->column('id');
    }
}
